'######################################################################################
'Author            :         Sumit Gupta 
'Company           :		     Vikasumit
'Date              :         7th August 2005
'Last Revised Date :         19th September 2007
'.NET Framework    :         2.0
'--------------------------------------------------------------------------------------
'Working / Note on File : 
'This file will read the XML document for the Given Application and Provides value as 
'required

'It will also allow the writing to the XML Document. Mainly for the Utilization of the
'Application Configuration
'######################################################################################

Imports System.Xml
Imports System.IO

Public Class clsXML

#Region "Private Temparory Varibles for Properties"

  Private Const CON_CLASSVERSION As String = "1.1.20070919" 'Define the Class Version
  Private t_XMLFile As String
  Private t_ConfigurationFor As String
  Private t_ErrorModeSilent As Boolean

#End Region

#Region "Public Events"

  Public Event FileNotFound() 'Error when File not Found
  Public Event ErrorHandler(ByVal msg As String)

#End Region

#Region "Public Property"

  'Get the Class Version
  Public ReadOnly Property ClassVersion() As String
    Get
      Return CON_CLASSVERSION
    End Get
  End Property

  Public Property ConfigurationFile() As String
    Get
      Return t_XMLFile
    End Get
    Set(ByVal Value As String)
      t_XMLFile = Value
    End Set
  End Property

  Public Property ConfigurationFor() As String
    Get
      Return t_ConfigurationFor
    End Get
    Set(ByVal Value As String)
      t_ConfigurationFor = Value
    End Set
  End Property

  Public Property ErrorModeSilent() As Boolean
    Get
      Return t_ErrorModeSilent
    End Get
    Set(ByVal value As Boolean)
      t_ErrorModeSilent = value
    End Set
  End Property

#End Region

#Region "Public Functions"

#Region "Constructor"

  'Default it initialize things only
  Public Sub New()
    Initialize()
  End Sub

#End Region

  'Function to read value from XML file
  Public Function GetValue(ByVal section As String, ByVal Key As String) As String
    If t_XMLFile = "" Then
      RaiseEvent FileNotFound()
      Return "FALSE"
    Else
      'File is defined
      If (File.Exists(Me.ConfigurationFile)) Then
        Return DoFileReading(section, Key)
      Else
        RaiseEvent FileNotFound()
        Return "FALSE"
      End If

    End If
  End Function

  'Function to Set the Value 
  Public Function SetValue(ByVal section As String, ByVal Key As String, ByVal value As String) As Boolean
    If t_XMLFile = "" Then
      RaiseEvent FileNotFound()
      Return False
    Else
      Return WriteXMLFile(section, Key, value)
    End If
  End Function

  Public Function CreateBlankConfigurationFile() As Boolean
    If Me.ConfigurationFile = "" Then
      RaiseEvent ErrorHandler("Configuration file not define")
      If Not Me.ErrorModeSilent Then
        MsgBox("Configuration file not define")
      End If
      Return False
    End If
    If (File.Exists(Me.ConfigurationFile)) Then
      If MsgBox("Old Configuration file already exists. Are you sure to overwrite that file?", MsgBoxStyle.OkCancel, Me.ConfigurationFor) = MsgBoxResult.Ok Then
        Try
          File.Delete(Me.ConfigurationFile)
        Catch ex As Exception
          RaiseEvent ErrorHandler("Unable to delete old configuration file")
          If Not Me.ErrorModeSilent Then
            MsgBox("Unable to delete old configuration file" & vbCrLf & ex.Message)
          End If
        End Try
        Return DoCreateConfigurationFile()
      Else
        Exit Function
        Return False
      End If
    Else
      'Create new file
      Return DoCreateConfigurationFile()
    End If
  End Function

#End Region

#Region "Private Functions"

  Private Sub Initialize()
    'Current a blank function
    Me.ErrorModeSilent = False
  End Sub

  Private Function DoCreateConfigurationFile() As Boolean
    Dim xmldoc As New XmlDocument
    Dim xmldec As XmlDeclaration
    xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", "yes")
    xmldoc.InsertBefore(xmldec, xmldoc.DocumentElement)
    Dim xmlcomment As XmlComment
    xmlcomment = xmldoc.CreateComment("Configuration File Created Using Vikasumit Configuration Utility for " & Me.ConfigurationFor)
    xmldoc.InsertAfter(xmlcomment, xmldec)
    Dim xmlroot As XmlElement = xmldoc.CreateElement("Configuration")
    xmldoc.InsertAfter(xmlroot, xmlcomment)
    Try
      xmldoc.Save(Me.ConfigurationFile)
      Return True
    Catch ex As Exception
      RaiseEvent ErrorHandler("Unable to save the configuration file")
      If Not Me.ErrorModeSilent Then
        MsgBox("Unable to save the configuration file." & vbCrLf & ex.Message)
      End If
      Return False
    End Try
  End Function

  Private Function DoFileReading(ByVal section As String, ByVal Key As String) As String
    Try
      Dim xmlDoc As New XmlDocument
      Dim Node As XmlNode
      Try
        xmlDoc.Load(Me.ConfigurationFile)
      Catch ex As Exception
        RaiseEvent ErrorHandler("Unable to open Configuration File. Exception throw is" & vbCrLf & ex.Message)
        If Not Me.ErrorModeSilent Then
          MsgBox("Unable to open Configuration file.")
        End If
      End Try
      Node = xmlDoc.SelectSingleNode("//Configuration/Section[@name='" & section & "'][Key='" & Key & "']")
      If Not Node Is Nothing Then
        Return Node.SelectSingleNode("Value").InnerText
      Else
        Return "FALSE"
      End If
    Catch ex As Exception
      RaiseEvent ErrorHandler("An Exception has occcured while reading configuration. Exception is " & vbCrLf & ex.Message)
      Return "FALSE"
    End Try

  End Function

  Private Function WriteXMLFile(ByVal section As String, ByVal Key As String, ByVal value As String) As Boolean
    Dim xmlDoc As XmlDocument
    Dim Node As XmlNode

    xmlDoc = New XmlDocument
    Try
      xmlDoc.Load(Me.ConfigurationFile)
    Catch ex As Exception
      RaiseEvent ErrorHandler("Unable to open Configuration File. Exception throw is" & vbCrLf & ex.Message)
      If Not Me.ErrorModeSilent Then
        MsgBox("Unable to open Configuration file.")
      End If
    End Try

    Dim xmlroot As XmlNode = xmlDoc.SelectSingleNode("//Configuration")

    Node = xmlDoc.SelectSingleNode("//Configuration/Section[@name='" & section & "'][Key='" & Key & "']")
    If Not Node Is Nothing Then
      Dim xNode As XmlNode = Node.SelectSingleNode("Value")
      xNode.InnerText = value
    Else
      Dim xmlSection As XmlElement = xmlDoc.CreateElement("Section")
      Dim xmlKey As XmlElement = xmlDoc.CreateElement("Key")
      Dim xmlValue As XmlElement = xmlDoc.CreateElement("Value")
      Dim xmlname As XmlAttribute = xmlDoc.CreateAttribute("name")

      xmlname.Value = section
      xmlValue.InnerText = value
      xmlKey.InnerText = Key

      xmlSection.AppendChild(xmlKey)
      xmlSection.AppendChild(xmlValue)
      xmlSection.SetAttributeNode(xmlname)

      xmlroot.AppendChild(xmlSection)
    End If
    Try
      xmlDoc.Save(Me.ConfigurationFile)
    Catch ex As Exception
      RaiseEvent ErrorHandler("Fail to write the configuration file")
      If Not Me.ErrorModeSilent Then
        MsgBox("Fail to write the configuration file " & vbCrLf & ex.Message)
      End If
    Finally
      xmlDoc = Nothing
    End Try
  End Function
#End Region

End Class